package com.test.clyq.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.test.Constants;
import com.test.clyq.entity.Question;
import com.test.clyq.entity.QuestionCategory;
import com.test.clyq.entity.Users;
import com.test.clyq.service.QuestionCategoryService;
import com.test.clyq.service.QuestionService;
import com.test.json.JsonUtil;
import com.test.util.FormatExceptionStack;
import com.test.util.ObjectUtils;
import com.test.util.Pagination;
import com.test.util.SessionUtil;
import com.test.util.StringUtils;
import com.test.webapp.action.BaseAction;

/**
 * QuestionAction. <br>
 * 问题管理.
 * <p>
 * Copyright: Copyright (c) 2010-4-17 下午04:52:10
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: suncg@c-platform.com
 * <p>
 * Version: 1.0
 * <p>
 */
public class QuestionAction extends BaseAction {

	/**
	 * 添加一个问题
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward addQuestion(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("添加一个问题表start");
		QuestionService questionService = (QuestionService) getBean("questionService");
		QuestionCategoryService questionCategoryService = (QuestionCategoryService) getBean("questionCategoryService");
		Users user = SessionUtil.getUserFromSession(request);
		String categoryId = getParameter(request, "questionCategoryId");
		try {
			if (!ObjectUtils.isNull(user) && StringUtils.isNumeric(categoryId)) {
				QuestionCategory category = questionCategoryService.getOneQuestionCategory(Long.valueOf(categoryId));
				if (category != null) {
					Question question = new Question();
					question.setContent(getParameter(request, "content"));
					question.setEndDateStr(getParameter(request, "endDateStr"));
					question.setQuestionDesc(getParameter(request, "questionDesc"));
					// question.setType(getParameter(request, "type"));// FIXME
					question.setDate(System.currentTimeMillis());
					// question.setCategory(category);
					question.setCategoryQuestionId(Long.valueOf(categoryId));
					// question.setWebsite(user.getUsersWebsite());
					questionService.addQuestion(question, user);
					// print(response, true);
					this.log.debug("添加一个问题成功");
					this.log.info("添加一个问题end");
					print(response, true);
				} else {
					print(response, false);
				}
			} else {
				print(response, false);
			}
		}
		catch (Exception e) {
			this.log.error("添加一个问题:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}

	/**
	 * 删除问题
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward deleteQuestion(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("删除问题start");
		QuestionService questionService = (QuestionService) getBean("questionService");
		Users user = SessionUtil.getUserFromSession(request);
		try {
			if (!ObjectUtils.isNull(user)) {
				String questionId = getParameter(request, "questionId");
				if (StringUtils.isNumeric(questionId)) {
					questionService.deleteQuestion(Long.valueOf(questionId), user);
					print(response, true);
					this.log.debug("删除问题成功");
					this.log.info("删除问题end");
				}
			} else {
				print(response, false);
			}
		}
		catch (Exception e) {
			this.log.error("删除问题:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;

	}

	/**
	 * 获得一个问题
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward getQuestion(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("获得一个问题表start");
		QuestionService questionService = (QuestionService) getBean("questionService");
		Users user = SessionUtil.getUserFromSession(request);
		String questionId = getParameter(request, "questionId");
		try {
			if (!ObjectUtils.isNull(user) && StringUtils.isNumeric(questionId)) {
				Question question = questionService.getOneQuestion(Long.valueOf(questionId));
				if (!ObjectUtils.isNull(question)) {
					this.log.debug("获得一个问题成功");
					this.log.info("获得一个问题end");
					print(response, "{results:[{%s}]}", null, null, question.toJSON());
				} else {
					print(response, false);
				}

			} else {
				print(response, false);
			}

		}
		catch (Exception e) {
			this.log.error("获得一个问题:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}

	/**
	 * 获得问题列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward getQuestions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("获得问题列表start");
		QuestionService questionService = (QuestionService) getBean("questionService");
		try {
			String start = getParameter(request, "start");
			String limit = getParameter(request, "limit");
			String categoryId = getParameter(request, "questionCategoryId");
			int currpageNo = 1;
			int pageCount = Integer.parseInt(limit);
			if (Integer.parseInt(start) / pageCount != 0) {
				currpageNo = Integer.parseInt(start) / pageCount + 1;// 当前页码

			}
			Pagination pagination = new Pagination(currpageNo, pageCount);// 设置分页参数（页码和每页显示记录条数）
			int totalCount = 0;
			List<Question> list = questionService.getQuestionByPage(pagination, Long.valueOf(categoryId));
			totalCount = pagination.getTotalRows();
			String jsonStr = JsonUtil.getJsonStr(list, new String[] { "id", "content", "date", "endDateStr" }, new String[] { "date" }, totalCount);
			this.log.debug("获得问题列表成功");
			this.log.info("获得问题列表end");
			print(response, jsonStr, null, null);
		}
		catch (Exception e) {
			this.log.error("获得问题:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}

	/**
	 * 修改一个问题
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward updateQuestion(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("修改一个问题表start");
		QuestionService questionService = (QuestionService) getBean("questionService");
		Users user = SessionUtil.getUserFromSession(request);
		String questionId = getParameter(request, "id");
		try {
			if (!ObjectUtils.isNull(user) && StringUtils.isNumeric(questionId)) {
				Question question = questionService.getOneQuestion(Long.valueOf(questionId));
				question.setContent(getParameter(request, "content"));
				question.setEndDateStr(getParameter(request, "endDateStr"));
				question.setQuestionDesc(getParameter(request, "questionDesc"));
				question.setType(getParameter(request, "type"));// FIXME 暂时不开启
				questionService.updateQuestion(question, user);
				print(response, true);
				this.log.debug("修改一个问题成功");
				this.log.info("修改一个问题end");
			} else {
				print(response, false);
			}
		}
		catch (Exception e) {
			this.log.error("修改一个问题:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}

	/**
	 * 生成短连接
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward createUrl(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		log.info("生成短连接");
		QuestionService questionService = (QuestionService) getBean("questionService");
		Users user = SessionUtil.getUserFromSession(request);
		String questionId = getParameter(request, "questionId");
		try {
			if (!ObjectUtils.isNull(user) && StringUtils.isNumeric(questionId)) {
				Question question = questionService.getOneQuestion(Long.valueOf(questionId));
				if (!ObjectUtils.isNull(question)) {
					this.log.debug("获得一个问题成功");
					this.log.info("获得一个问题end");
					question.setEndDateStr(Constants.settings.get("URL_PATH") + "v-" + question.getId());
					String fragStr = "{results:[{" + question.toJSON() + "}]}";
					print(response, fragStr, null, null);
				}
			}

		}
		catch (Exception e) {
			this.log.error("生成短连接:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}
}
